package app.controllers;

import app.Const;
import app.models.system.Attachments;
import com.google.common.collect.Lists;
import com.ifonly.activerecord.ActiveRecordFactory;
import com.ifonly.activerecord.DbUtils;
import com.ifonly.mvc.Controller;
import com.ifonly.upload.IFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author ifonly
 * @version 1.0 2016-02-19 14:23
 * @since JDK 1.6
 */
public class FileController extends Controller {
    private Attachments dao = ActiveRecordFactory.getActiveRecord(Attachments.class);

    private static final String UPLOADS = "/uploads";

    public static String getUploadDir(HttpServletRequest request) {
        return request.getServletContext().getRealPath(UPLOADS);
    }

    /**
     * 文件上传
     */
    public void upload() {
        String uploadType = getParam("uploadType", Const.UploadType.IMAGE.name());
        String attachmentType = getParam("attachmentType");

        List<Attachments> attachmentses = Lists.newArrayList();

        Map<String, IFile[]> fileMap =  getFileMap();
        if (fileMap != null && !fileMap.isEmpty()) {
            Set<Map.Entry<String, IFile[]>> entrySet = fileMap.entrySet();
            for (Map.Entry<String, IFile[]> entry : entrySet) {
                IFile[] iFiles = entry.getValue();
                for (IFile iFile : iFiles) {
                    attachmentses.add(dao.upload(getUploadDir(getRequest()), uploadType, attachmentType, iFile));
                }
            }
        }

        renderSuccess(attachmentses);
    }


    public void delete() {
        long id = getLong(Const.ID);
        dao.delete(getUploadDir(getRequest()), id);
        renderSuccess();
    }

    public void render() {
        String data = getParam("data");
        List<Attachments> list = new ArrayList<Attachments>();
        if (data != null) {
            list = DbUtils.list(Attachments.class, "SELECT * FROM s_attachments WHERE id IN ("+ data +")");
        }
        renderSuccess(list);
    }

}
